package chapter13.eg1.broadcaster;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
import java.util.List;

public class LogEventEncoder extends MessageToMessageEncoder<LogEvent> {

  private final InetSocketAddress remoteAddress;

  public LogEventEncoder(InetSocketAddress remoteAddress) {
    this.remoteAddress = remoteAddress;
  }

  @Override
  protected void encode(ChannelHandlerContext ctx, LogEvent logEvent, List<Object> out)
      throws Exception {
    byte[] file = logEvent.getLogFile().getBytes(CharsetUtil.UTF_8);
    byte[] msg = logEvent.getMsg().getBytes(CharsetUtil.UTF_8);
    ByteBuf buffer = ctx.alloc().buffer(file.length + msg.length + 1);
    buffer.writeBytes(file)
        .writeByte(LogEvent.SEPARATOR)
        .writeBytes(msg);
    out.add(new DatagramPacket(buffer, remoteAddress));
  }
}
